//
//  LLLabelAddVC.m
//  LLLabel
//
//  Created by LQ on 2020/12/9.
//

#import "WKLabelAddVC.h"
#import "WKLabelConst.h"
@interface WKLabelAddVC ()

@end

@implementation WKLabelAddVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.viewModel = [WKLabelAddVM new];
    }
    return self;
}

- (void)viewDidLoad {
    self.viewModel.label = self.label;
    __weak typeof(self) weakSelf =self;
    self.viewModel.onUpdateFinishBtn = ^{
        [weakSelf updateFinishBtn];
    };
    
    [super viewDidLoad];
    self.finishBtn.enabled = NO;
    self.rightView = self.finishBtn;
    
    [self.finishBtn addTarget:self action:@selector(finishedPressed) forControlEvents:UIControlEventTouchUpInside];
   
}
- (NSString *)langTitle {
    return LLang(@"新建标签");
}

-(void) finishedPressed {
    __weak typeof(self) weakSelf = self;
    [weakSelf.view showHUD];
    [self.viewModel finishLabel].then(^{
        [weakSelf.view hideHud];
        [[WKNavigationManager shared] popViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:WK_NOTIFY_LABELLIST_REFRESH object:nil];
    }).catch(^(NSError *error){
        [weakSelf.view switchHUDError:error.domain];
    });
}

//点击右侧索引表项时调用 索引与section的对应关系
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index+self.viewModel.headerCount;
}

//section右侧index数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.viewModel.sectionTitleArr;
}


- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if(indexPath.section<self.viewModel.headerCount) {
        return @[];
    }
    UITableViewRowAction *action = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:LLang(@"删除") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        WKChannelInfo *memberChannelInfo = weakSelf.viewModel.members[indexPath.section - self.viewModel.headerCount][indexPath.row];
        if(memberChannelInfo) {
            [weakSelf.viewModel removeMemberWithUID:memberChannelInfo.channel.channelId];
        }
    }];
    return @[action];
}

- (void)reloadData {
    [super reloadData];
    [self updateFinishBtn];
}

-(void) updateFinishBtn {
    self.finishBtn.enabled = YES;
    if(!self.viewModel.labelName || [[self.viewModel.labelName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] isEqualToString:@""]) {
        self.finishBtn.enabled = NO;
        return;
    }
    if(!self.viewModel.memberItems || self.viewModel.memberItems.count<=0) {
        self.finishBtn.enabled = NO;
        return;
    }
}

@end
